package com.asking.filter;


import com.asking.utils.JWTUtil;
import io.jsonwebtoken.SignatureException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends GenericFilterBean {

    @Override
    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
            throws IOException, ServletException {

        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        final String authHeader = request.getHeader("token");
        final String uri = request.getRequestURI();


        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "token,Content-Type");
        response.setHeader("Access-Control-Expose-Headers", "*");
        System.out.println("OK!!!!!");
        System.out.println(uri);
//        if ("OPTIONS".equals(request.getMethod())) {
//            System.out.println("OPTIONS");
//            response.setStatus(HttpServletResponse.SC_OK);
//
//            chain.doFilter(req, res);
//        } else {
//            if(uri.contains("/login")||uri.contains("/regist")){
//                System.out.println("1111111111111111111111111111111111111111111111111111111111111");
//                chain.doFilter(request, response);
//                return;
//            }
//            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
//                throw new ServletException("未登录，请登录");
//            }
//
//            //如果请求路径是公用的
//            final String token = authHeader.substring(7);
//            try {
////                final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();
//
//                final String claims = JWTUtil.getUser(token);
//                String[] user = claims.split("#");
//                if (JWTUtil.verify(token,user[0],user[1])) {
//                    request.setAttribute("claims", claims);
//                }else{
//                    throw new ServletException("登录错误或失效");
//                }
//            } catch (final SignatureException e) {
//
//                throw new ServletException("登录错误或失效");
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new ServletException("登录错误或失效");
//            }
//            chain.doFilter(request, response);

            chain.doFilter(request, response);
//        }
    }
}
